package com.acando.feide;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.acando.feide.utils.AppException;

/**
 * Validation routines used in LDIF generation
 */
public class Validator {

    public void validatePerson(LDIFEntry person) throws AppException {

        // uid
        String uid = mandatorySingleCheck("uid", "person", person);
        // eduPersonPrincipalName
        String eduPersonPrincipalName = mandatorySingleCheck("eduPersonPrincipalName", "person", person);

        // Check uid / feideName
        String feideId = eduPersonPrincipalName.substring(0, eduPersonPrincipalName.indexOf("@"));
        if (!uid.equals(feideId)) {
            throw new AppException("LDAP attribute uid(" + uid + ")/eduPersonPrincipalName(" + eduPersonPrincipalName
                    + ") does not match for person with source id '" + person.getId() + "'");

        }
    }

    public void validateOrganization(LDIFEntry org) throws AppException {

        // norEduOrgNIN
        String norEduOrgNIN = mandatorySingleCheck("norEduOrgNIN", "organization", org);
        String expression = "^NO[0-9]{9}";
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(norEduOrgNIN);
        if (!matcher.matches()) {
            throw new AppException("Format error on norEduOrgNIN '" + norEduOrgNIN
                    + "' in an organization with source id '" + org.getId() + "'");
        }
    }

    public void validateOrganizationUnit(LDIFEntry unit) throws AppException {

        // norEduOrgUnitUniqueIdentifier
        String norEduOrgUnitUniqueIdentifier = mandatorySingleCheck("norEduOrgUnitUniqueIdentifier", "organizational Unit", unit);
        String expression = "^NO[0-9]{9}";
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(norEduOrgUnitUniqueIdentifier);
        if (!matcher.matches()) {
            throw new AppException("Format error on norEduOrgUnitUniqueIdentifier '" + norEduOrgUnitUniqueIdentifier
                    + "' in an organizational unit with source id '" + unit.getId() + "'");
        }
    }

    private String mandatorySingleCheck(String attrName, String entryName, LDIFEntry entry) throws AppException {
        if (entry.findItem(attrName).getValues().size() == 0 || entry.findItem(attrName).getValues().get(0).isEmpty()) {
            throw new AppException("LDAP attribute " + attrName + " missing for " + entryName + " with source id '"
                    + entry.getId() + "'");
        } else {
            return entry.findItem(attrName).getValues().get(0);
        }
    }
}
